package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.lock.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * date: 2023/9/13 12:19
 * author: MR.孙
 */
public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";

    //去掉-符号的UUID
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private final String name;

    private final StringRedisTemplate stringRedisTemplate;

    private final static DefaultRedisScript<Long> UNLOCK_SCRIPT;

    //应当类加载时就执行lua脚本的加载，而不是在释放锁的时候
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     *
     * @param timeoutSec 锁持有的超时时间，过期后自动释放
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //值不能随便设置，防止删除其他线程持有的锁，导致更多的线程进来
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean ifAbsent = stringRedisTemplate.opsForValue().
                setIfAbsent(KEY_PREFIX + name,
                        threadId,
                        timeoutSec,
                        TimeUnit.SECONDS);
        return BooleanUtil.isTrue(ifAbsent);
    }

    /**
     * 释放锁 使用lua脚本保证释放锁时的原子性【lua脚本判断当前线程标识和锁中的线程标识是否一致，一致即删除】
     */
    @Override
    public void unlock() {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                threadId);
    }


    /*@Override
    public void unlock() {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁中的值标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //删锁的时候比对uuid + 线程标识与锁中的值是否一致
        if (threadId.equals(id)) {
            //释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);

        }

    }*/



}
